package com.riko.comic.module.comic.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.riko.comic.module.comic.bean.po.*;
import com.riko.comic.module.comic.bean.vo.ComicCommentsVo;
import com.riko.comic.module.comic.mapper.ComicCommentsMapper;
import com.riko.comic.module.comic.service.IChapterService;
import com.riko.comic.module.comic.service.IComicCommentsService;
import com.riko.comic.module.comic.service.IComicService;
import com.riko.comic.module.sys.service.IComicRankService;
import com.riko.comic.module.comic.service.*;
import com.riko.comic.module.sys.bean.po.User;
import com.riko.comic.module.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xt
 * @since 2021/11/01
 */
@Controller
@RequestMapping("/comic")
public class ComicController {

    @Autowired
    private IComicService comicService;

    @Autowired
    private IChapterService chapterService;

    @Autowired
    private IComicCommentsService comicCommentsService;

    @Autowired
    private ComicCommentsMapper comicCommentsMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IComicRankService comicRankService;

    @Autowired
    private IVisitLogService visitLogService;

    @Autowired
    private ICloutService cloutService;

    @RequestMapping("/{comicName}")
    public String queryComic(HttpServletRequest request, @PathVariable() String comicName){
        Comic comic = comicService.getOne(Wrappers.lambdaQuery(Comic.class).eq(Comic::getPinyin, comicName));
        long chapterNumber = chapterService.count(Wrappers.lambdaQuery(Chapter.class).eq(Chapter::getComicId,comic.getId()));
        Double avgScore = comicRankService.queryAvgScore(comic.getId());

        List<Integer> chapterNumberList = new ArrayList<>();
        for(int i = 1; i<=chapterNumber; i++){
            chapterNumberList.add(i);
        }

        List<ComicCommentsVo> comments = new ArrayList<>();
        for (ComicComments comicComments : comicCommentsMapper.queryComments(comic.getId())) {
            ComicCommentsVo comicCommentsVo = new ComicCommentsVo();
            comicCommentsVo.setComments(comicComments);
            comicCommentsVo.setNick(userService.getById(comicComments.getUserId()).getNick());
            comicCommentsVo.setPic(userService.getById(comicComments.getUserId()).getPic());
            comments.add(comicCommentsVo);
        }

        request.setAttribute("comments",comments);
        request.setAttribute("chapterNumberList",chapterNumberList);
        request.setAttribute("comic",comic);

        if(avgScore == null){
            request.setAttribute("avgScore", "暂无评分");
        } else {
            request.setAttribute("avgScore",String.format("%.2f", avgScore));
        }

        return "comic";
    }

    @RequestMapping("/{comicName}/chapter/{number}/coin")
    public void coin(HttpSession session, HttpServletResponse response, @PathVariable String comicName, @PathVariable String number) throws IOException {
        Comic comic = comicService.getOne(Wrappers.lambdaQuery(Comic.class).eq(Comic::getPinyin, comicName));
        Chapter chapter = chapterService.getOne(
                Wrappers.lambdaQuery(Chapter.class)
                .eq(Chapter::getChapterNumber,number)
                .eq(Chapter::getComicId,comic.getId()));

        Integer userId = (Integer) session.getAttribute("loginUserId");
        User user = userService.getById(userId);

        List<VisitLog> visitLogList1 = visitLogService.list(
                Wrappers.lambdaQuery(VisitLog.class)
                .eq(VisitLog::getUserId,userId)
                .eq(VisitLog::getComicId,comic.getId())
                .eq(VisitLog::getChapterId,chapter.getId())
        );
        if(visitLogList1.toString().equals("[]")){
            if(user.getCoin()<50){
                response.getWriter().write("error");
                return;
            }else {
                user.setCoin(user.getCoin()-50);
                userService.updateById(user);

                //添加访问记录
                VisitLog visitLog = new VisitLog();
                visitLog.setUserId(userId);
                visitLog.setComicId(comic.getId());
                visitLog.setChapterId(chapterService.
                        getOne(Wrappers.lambdaQuery(Chapter.class)
                                .eq(Chapter::getChapterNumber,number)
                                .eq(Chapter::getComicId,comic.getId())
                        ).getId());
                visitLog.setCreateTime(LocalDateTime.now());
                visitLogService.save(visitLog);

                //添加漫画热度
                Clout one = cloutService.getOne(
                        Wrappers.lambdaQuery(Clout.class)
                                .eq(Clout::getComicId, comic.getId())
                                .eq(Clout::getCreateDate, LocalDate.now())
                );
                if(one == null){
                    Clout clout = new Clout();
                    clout.setComicId(comic.getId());
                    clout.setCount(1);
                    clout.setCreateDate(LocalDate.now());
                    cloutService.save(clout);
                }else {
                    Clout clout = cloutService.getOne(Wrappers.lambdaQuery(Clout.class).eq(Clout::getComicId, comic.getId()).eq(Clout::getCreateDate, LocalDate.now()));
                    clout.setCount(clout.getCount()+1);
                    cloutService.updateById(clout);
                }
                response.getWriter().write("success");
                return;
            }
        }

        //一个用户对一个漫画的一个章节一天内的访问只记录一次流量
        List<VisitLog> visitLogList2 = visitLogService.list(
                Wrappers.lambdaQuery(VisitLog.class)
                        .eq(VisitLog::getUserId,userId)
                        .eq(VisitLog::getComicId,comic.getId())
                        .eq(VisitLog::getChapterId,chapter.getId())
                        .like(VisitLog::getCreateTime,LocalDate.now())
        );

        //添加访问记录
        VisitLog visitLog = new VisitLog();
        visitLog.setUserId(userId);
        visitLog.setComicId(comic.getId());
        visitLog.setChapterId(chapterService.
                getOne(Wrappers.lambdaQuery(Chapter.class)
                        .eq(Chapter::getChapterNumber,number)
                        .eq(Chapter::getComicId,comic.getId())
                ).getId());
        visitLog.setCreateTime(LocalDateTime.now());
        visitLogService.save(visitLog);

        if(visitLogList2.toString().equals("[]")){
            Clout one = cloutService.getOne(
                    Wrappers.lambdaQuery(Clout.class)
                            .eq(Clout::getComicId, comic.getId())
                            .eq(Clout::getCreateDate, LocalDate.now())
            );
            if(one == null){
                Clout clout = new Clout();
                clout.setComicId(comic.getId());
                clout.setCount(1);
                clout.setCreateDate(LocalDate.now());
                cloutService.save(clout);
            }else {
                Clout clout = cloutService.getOne(Wrappers.lambdaQuery(Clout.class).eq(Clout::getComicId, comic.getId()).eq(Clout::getCreateDate, LocalDate.now()));
                clout.setCount(clout.getCount()+1);
                cloutService.updateById(clout);
            }
        }

        response.getWriter().write("success");
    }

    @RequestMapping("/{comicName}/chapter/{number}")
    public String queryChapter(HttpServletRequest request, @PathVariable() String comicName, @PathVariable() String number){
        Comic comic = comicService.getOne(Wrappers.lambdaQuery(Comic.class).eq(Comic::getPinyin, comicName));
        Long chapterNumber = chapterService.count(Wrappers.lambdaQuery(Chapter.class).eq(Chapter::getComicId,comic.getId()));

        List<ChapterImg> chapterImgList=comicService.queryChapterImg(comicName,number);

        request.setAttribute("chapterNumber",chapterNumber);
        request.setAttribute("CurrentChapter",number);
        request.setAttribute("comicName",comicName);
        request.setAttribute("chapterImgList",chapterImgList);

        return "chapter";
    }

    @RequestMapping("/{comicName}/comment")
    public String comment(HttpServletRequest request, @RequestParam("newComment") String newComment, @PathVariable String comicName){
        HttpSession session = request.getSession();

        Comic comic = comicService.getOne(Wrappers.lambdaQuery(Comic.class).eq(Comic::getPinyin, comicName));

        ComicComments comments = new ComicComments();
        comments.setUserId((Integer) session.getAttribute("loginUserId"));

        comments.setComicId(comic.getId());
        comments.setCommentTime(LocalDateTime.now());
        comments.setComment(newComment);

        comicCommentsService.saveOrUpdate(comments);

        return "redirect:/comic/" + comicName;
    }
}
